package com.holyn.guofang.model.webhttp;

import com.holyn.guofang.MyApplication;
import com.holyn.guofang.model.sharepreference.UserInfoSharePreference;
import com.holyn.guofang.model.webhttp.cookie.CookieJarImpl;
import com.holyn.guofang.model.webhttp.cookie.store.PersistentCookieStore;
import com.holyn.guofang.model.webhttp.interceptor.BasicParamsInterceptor;
import com.holyn.guofang.model.webhttp.observable.UserUnLoginObservable;
import com.holyn.guofang.utils.AppUniqueInfoUtil;
import com.holyn.guofang.utils.MD5Uitl;
import com.holyn.guofang.utils.RandomUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Holyn on 2017/4/26.
 */

public class RetrofitManager {
    public static Retrofit commonRetrofit;
    public static Retrofit downloadRetrofit;

    public static <T> T getCommonObservable(final Class<T> tClass){
        String tSimpleName = tClass.getSimpleName();
        if (tSimpleName.equals(UserUnLoginObservable.class.getSimpleName())){
            return getCommonRetrofit(false).create(tClass);
        } else {
            return getCommonRetrofit(true).create(tClass);
        }
    }

    private static Retrofit getCommonRetrofit(boolean isLogin){
        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true) // 是否重试
                .readTimeout(30, TimeUnit.MINUTES)//设置新连接默认读取超时时长
                .connectTimeout(10, TimeUnit.MINUTES)//设置新连接的默认连接超时时长
//                .cookieJar(new CookieJarImpl(new MemoryCookieStore()))//cookie使用内存缓存（app退出后，cookie消失）
                .cookieJar(new CookieJarImpl(new PersistentCookieStore()));//cookie持久化存储，如果cookie不过期，则一直有效

        httpBuilder.addInterceptor(getBasicParamsInterceptor(isLogin));

        if (HttpConfigure.IS_DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpBuilder.addInterceptor(interceptor);
        }

        Retrofit retrofit = new Retrofit.Builder().baseUrl(HttpConfigure.BASE_URL)
                .client(httpBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        return retrofit;
    }

    /**
     *
     * 登录前：
     * platformType 平台类型(1:IOS 以外平台，2:IOS)
     * isWeb 是否为网页端登录(1:是，0:否)
     * device 设备唯一标识，网页端统一传 web
     * rand 随机字符串(网页端不用传该值，其他平台该值不 能为空或空字符串)
     * checkCode 验证码，网页端使用输入图片显示的验证码(保存 到 Session 中)，其他平台使用对字符串
     *                  platformCheckCode=平台验证码&rand=随机字符串进行32位MD5加密后的字符串
     *
     * 登录后：
     * platformType 平台类型(1:IOS 以外平台，2:IOS)
     * isWeb 是否为网页端登录(1:是，0:否)
     * userID 用户ID
     * loginID 登录ID
     * rand 随机字符串(网页端不用传该值，其他平台该值不 能为空或空字符串)
     * checkCode "platformCheckCode=平 台 验 证 码&userID=用 户ID&loginID=登 录ID
     *                  &loginCheckCode=登 录 验 证码&rand=随机字符串"
     *                  这个字符串经 32 位 MD5 加密
     *
     * @FormUrlEncoded
     * @POST
     * @Field
     *
     * @return
     */
    private static BasicParamsInterceptor getBasicParamsInterceptor(boolean isLogin){
        Integer platformType = HttpConfigure.PLATFORM_TYPE_ANDROID;
        Integer isWeb = HttpConfigure.IS_WEB_FALSE;
        String device = new AppUniqueInfoUtil(MyApplication.getContext()).getUniqueID();
        String userID = UserInfoSharePreference.getUserID(MyApplication.getContext());
        String loginID = UserInfoSharePreference.getLoginID(MyApplication.getContext());
        String loginCheckCode = UserInfoSharePreference.getCheckCode(MyApplication.getContext());
        String rand = RandomUtil.createRandom(false,8);
        String checkCode = MD5Uitl.getMd5Value("platformCheckCode="+HttpConfigure.PLATFORM_CHECK_CODE + "&"+"rand="+rand);
        if (isLogin){
            checkCode = MD5Uitl.getMd5Value("platformCheckCode="+HttpConfigure.PLATFORM_CHECK_CODE
                    + "&"+"userID="+userID
                    + "&"+"loginID="+loginID
                    + "&"+"loginCheckCode="+loginCheckCode
                    + "&"+"rand="+rand);
        }

        BasicParamsInterceptor.Builder builder = new BasicParamsInterceptor.Builder();
        builder.addParam("platformType", platformType+"");
        builder.addParam("isWeb", isWeb+"");
        System.out.println("========> device: "+ device);
        builder.addParam("device", device);
        if (isLogin){
            builder.addParam("userID", userID);
            builder.addParam("loginID", loginID);
        }
        builder.addParam("rand", rand);
        builder.addParam("checkCode", checkCode);

        return builder.build();
    }

}
